package com.avic.rong.search.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.avic.rong.MyApplication;
import com.avic.rong.R;
import com.avic.rong.search.db.User;
import com.avic.rong.search.db.UserDao;

import java.util.List;

/**
 * Created by uncleChen on 2019/7/20.
 */
public class SearchViewHomeJiLuRvAdapter extends RecyclerView.Adapter<SearchViewHomeJiLuRvAdapter.SearchViewHomeJiLuRvViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private List<String> list;
    private SearchJiLuListener listener;
    boolean userFlag = false;

    public void setListener(SearchJiLuListener listener) {
        this.listener = listener;
    }

    private static int maxItem = 8;

    public SearchViewHomeJiLuRvAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
        this.inflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public SearchViewHomeJiLuRvViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.view_search_home_jilu, viewGroup, false);
        return new SearchViewHomeJiLuRvViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SearchViewHomeJiLuRvViewHolder holder, int i) {

        holder.tv.setText(list.get(i));
        holder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserDao userDao = MyApplication.getInstance().getDaoSession().getUserDao();
                User user = new User();
                user.setText(list.get(i));
                user.setId(null);
                List<User> users = userDao.loadAll();
                for (int i=0;i<users.size();i++){
                    if (users.get(i).getText().equals(user.getText())){
                        userFlag = true;
                    }
                }
                if (!userFlag){
                    userDao.save(user);
                }
                listener.onClickItem(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (list.size() < 14)
            return list.size();
        else
            return 14;
    }

    class SearchViewHomeJiLuRvViewHolder extends RecyclerView.ViewHolder {
        TextView tv;

        public SearchViewHomeJiLuRvViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.searchView_Home_JuLu_TvItem);
        }
    }
    public interface SearchJiLuListener{
        void onClickItem(int i);
    }
}
